<?php

namespace App\Http\Controllers\Admin\Exts;

use App\Http\Controllers\Controller;
use App\Qingwuit\Models\Address;
use App\Qingwuit\Models\Area;
use App\Qingwuit\Models\Parlours;
use App\Qingwuit\Models\Riders;
use App\Qingwuit\Models\Store;
use App\Qingwuit\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use function PHPUnit\Framework\isInstanceOf;

class ParloursController extends Controller
{
    protected $modelName = 'parlours';
    //商铺补全信息
    public function completion (Request $request)
    {

        $user_id = $this->getUserId('users');
//        $user_id = 139;
        if (!$user_id) {
            return response()->json(['message' => '用户不存在'], 404);
        }
        $inite = User::where('id',$user_id)->first();
        $identity = $inite->identity;
//        dd($identity);
        if ($identity == 1){
            $data = Parlours::where('userid', $user_id)->first();

            if ($data){
                $data->parlour_phone = $request->parlour_phone;
                $data->avatar = $request->avatar;
                $data->business_license = $request->business_license;
                $data->parlour_name = $request->parlour_name;
                $data->parlour_contacts = $request->parlour_contacts;
                $data->address = $request->address;
                $data->longitude = $request->longitude;
                $data->latitude = $request->latitude;
                $data->save();
                $arr = [
                    'user_id' => $user_id,
                    'receive_name' => $request->parlour_contacts,
                    'receive_tel' => $request->parlour_phone,
                    'address' => $request->address,
                ];
                Address::updateOrCreate(['user_id' => $user_id], $arr);

                return $this->success('填写成功');
            }else{
                $arr= [
                    'parlour_phone' => $inite->username,
                    'userid'        => $user_id
                ];
                $this->getService('parlours', true)->create($arr);

                $data->parlour_phone = $request->parlour_phone;
                $data->avatar = $request->avatar;
                $data->business_license = $request->business_license;
                $data->parlour_name = $request->parlour_name;
                $data->parlour_contacts = $request->parlour_contacts;
                $data->address = $request->address;
                $data->longitude = $request->longitude;
                $data->latitude = $request->latitude;
                $data->save();
                $arr1 = [
                    'user_id' => $user_id,
                    'receive_name' => $request->parlour_contacts,
                    'receive_tel' => $request->parlour_phone,
                    'address' => $request->address,
                ];
                Address::updateOrCreate(['user_id' => $user_id], $arr1);

                return $this->success('填写成功');
            }
        }

        if ($identity == 2){
            $data = Riders::where('user_id', $user_id)->first();
            if ($data){
                $data->picture = $request->picture;
                $data->name = $request->name;
                $data->phone = $request->phone;
                if (preg_match("/^1[3-9]\d{9}$/", $request->phone)) {
                    // 手机号有效
                    $data->phone = $request->phone;
                } else {
                    return $this->error('手机号无效');
                }
                $data->gender = $request->gender;
                $data->cardid = $request->cardid;
                $id_card = $this->checkIdCard($data->cardid);
                if($id_card==false){
                    return $this->error('身份证号验证失败');
                }
                $data->driving_license = $request->driving_license;
                $data->vehicle_model = $request->vehicle_model;
                $data->save();

                return $this->success('填写成功');
            }
            return $this->error('填写失败');
        }

        if ($identity == 3){
            $data = Store::where('user_id', $user_id)->first();
//            dd($data);
            if ($data){
                $data->store_logo = $request->store_logo;
                $data->store_name = $request->store_name;
                $data->store_description = $request->store_description;
                $data->legal_person = $request->legal_person;
                $data->store_phone = $request->store_phone;
                $data->store_address = $request->store_address;
                $data->store_face_image = $request->store_face_image;
                $data->business_license = $request->business_license;
                $full_url = asset($request->business_license);
////                dd($full_url);
                if ($data->isvalidate== 0){
                $business = $this->query($full_url);
//                dd($business);
                if ($business['code']!= 1){
                   return $this->error('【营业执照】'.$business['msg']);
                }

                    $data->business_license_no  =    $business['result']['社会信用代码']['words'];
                    $data->legal_person         =    $business['result']['法人']['words'];
                    $data->store_company_name   =    $business['result']['单位名称']['words'];
                    $data->area_info            =    $business['result']['地址']['words'];
                    $data->isvalidate = 1;
                    $stors = Store::where('business_license_no',$data->business_license_no)->first();
                    if ($stors) return $this->error('营业执照已被认证');
                }


                $addressParts = $this->extractProvinceCityDistrict($request->store_address);
//                dd($addressParts);
                $province = Area::where('name',$addressParts['province'])->first();
                $city = Area::where('name',$addressParts['city'])->first();
                $region_id = Area::where('name',$addressParts['district'])->first();
                if($city->deep == 0){
                    $city = Area::where('pid',$city->code)->first();
                }
                $data->province_id = $province->id;
                $data->city_id = $city->id;
                $data->region_id = $region_id->id;
//                $data->area_info = $province->name.' '.$city->name.' '.$region_id->name;
                $data->save();
                return $this->success('填写成功');
            }
            return $this->error('填写失败');
        }
    }

    function extractProvinceCityDistrict($address) {
        $pattern = '/^(?<province>[^省]+省|[^自治区]+自治区|[^市]+市)(?<city>[^市]+市|[^县]+县)(?<district>[^区]+区|[^县]+县)?(?<street>.*)/u';
        preg_match($pattern, $address, $matches);

        $result = [];
        foreach (['province', 'city', 'district'] as $part) {
            if (isset($matches[$part]) && $matches[$part] != '') {
                $result[$part] = $matches[$part];
            }
        }

        return $result;
    }
    //分类
    public function goodsClasses()
    {
        $data = DB::table('goods_classes')
            ->where('pid',0)
            ->whereNull('deleted_at')
            ->get();
        return $this->success($data);
    }


    /**
     * 验证身份证
     * @param $id_card
     * @return bool
     * @throws ApiException
     */
     function checkIdCard($id_card): bool
    {
        // 仅仅能是18位
        if (strlen($id_card) != 18) {
           return false;
        }
        // 取出本体码
        $id_card_base = substr($id_card, 0, 17);
        // 取出校验码
        $verify_code = substr($id_card, 17, 1);
        // 加权因子
        $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
        // 校验码相应值
        $verify_code_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
        // 依据前17位计算校验码
        $total = 0;
        for ($i = 0; $i < 17; $i++) {
            $total += substr($id_card_base, $i, 1) * $factor[$i];
        }
        // 取模
        $mod = $total % 11;
        // 比較校验码
        if ($verify_code != $verify_code_list[$mod]) {
            return false;
        }
        return true;
    }


    /**
     * 获取身份证号的性别
     * @param string $id_card
     * @return int
     */
    public static function getSex(string $id_card): int
    {
        //获取身份证号的倒数第二位
        $last = substr($id_card, -2, 1);
        //判断性别 奇数为男 偶数为女
        if ($last % 2 == 0) {
            return 2;
        } else {
            return 1;
        }
    }

    /**
     * 获取身份证号的出生日期
     * @param string $id_card
     * @return string
     */
    public static function getBirthday(string $id_card): string
    {
        // 提取出生日期部分
        $birthdate = substr($id_card, 6, 8);
        // 格式化出生日期为YYYY-MM-DD
        $year = substr($birthdate, 0, 4);
        $month = substr($birthdate, 4, 2);
        $day = substr($birthdate, 6, 2);
        return $year . '-' . $month . '-' . $day;
    }


    function query($url)
    {
        $host = "https://bnesslic.market.alicloudapi.com";
        $path = "/buslicense";
        $method = "POST";
        $appcode = "f585325fd016446b837425ba2bb2bec7"; //开通服务后 买家中心-查看AppCode
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type: application/x-www-form-urlencoded; charset=UTF-8");

        $bodys = "image=" . urlencode($url);

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $host . $path);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);

        if (strpos("$" . $host, "https://") == 1) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $out_put = curl_exec($curl);

        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        list($header, $body) = explode("\r\n\r\n", $out_put, 2);
        if ($httpCode == 200) {
            return json_decode($body, true);
        } else {
            $errorMessages = [
                400 => [
                    "Invalid Param Location" => "参数错误",
                    "Invalid AppCode" => "AppCode错误",
                    "Invalid Url" => "请求的 Method、Path 或者环境错误",
                ],
                403 => [
                    "Unauthorized" => "服务未被授权（或URL和Path不正确）",
                    "Quota Exhausted" => "套餐包次数用完",
                    "Api Market Subscription quota exhausted" => "套餐包次数用完，请续购套餐",
                ],
                500 => "API网关错误",
                0 => "URL错误"
            ];

            foreach ($errorMessages as $code => $messages) {
                if ($httpCode == $code) {
                    if (is_array($messages)) {
                        foreach ($messages as $key => $message) {
                            if (strpos($header, $key) !== false) {
                                return ["error" => $message];
                            }
                        }
                    } else {
                        return ["error" => $messages];
                    }
                }
            }
            return ["error" => "参数名错误 或 其他错误", "httpCode" => $httpCode, "x-ca-error-message" => $header];
        }
    }

}
